<html>
<head>
<script src="jquery-1.5.1.min.js"></script>
</head>
<body>
<script>
var defaultParams =
{
	threads: {
		threshold: 3,
		size: 15,
		sort: 'updated'
	}
};

var remote =
{
	host: '10.14.87.101',
	load: function(method, params, callback) {
		if(params && $.isFunction(params)) {
			callback = params;
			params = {};
		}

		var data = {};
		if(defaultParams[method]) {
			$.extend(data, defaultParams[method]);
		}
		$.ajax('http://'+this.host+'/chatterplus/'+method, {
			data: $.extend(data, params),
			dataType: 'json',
			success: callback
		});
	}
};

var proxy =
{
	cache: {},

	cacheSpec: {
		threads: {
			root: 'threads', key: 'threadId'
		}
	},

	load: function(method, callback) {
		if(this.cache[method]) {
			callback(this.cache[method]);
		}
		else {
			var cache = this.cache;
			remote.load(method, function(json) {
				cache[method] = json;
				callback(json);
			});
		}
	},

	poll: function() {
		var me = this;
		$.each(this.cache, function(method, data) {
			remote.load(method, { size: 1 }, function(json) {
				me.refreshCache(method, data, json);
			});
		});
	},

	refreshCache: function(method, oldData, newData) {
		var spec = this.cacheSpec[method];
		if(oldData[spec.root][0][spec.key] != newData[spec.root][0][spec.key]) {
			delete this.cache[method];
		}
	}
};

var proc =
{
	hotentries: function(callback) {
		proxy.load('threads', callback);
	}
};


// Check new entry every 10 minutes.
setInterval(function() {
	proxy.poll.call(proxy);
}, 10*60*1000);


chrome.extension.onRequest.addListener(
	function (request, sender, callback) {
		var action = proc[request.action] || null;
		if(action && $.isFunction(action)) {
			action.call(proc, callback);
		}
	}
);
</script>
</body>
</html>
